/* 
 * Activator.java
 * Copyright (c) 2008 WayfarerX.net and others (see below).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * Contributors:
 *   WayfarerX (2008) - Initial documentation & implementation.
 * 
 */
package net.wayfarerx.tools.export.internal;

import java.util.concurrent.atomic.AtomicReference;

import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

/**
 * Activator for the export tools bundle.
 * 
 * @author WayfarerX
 */
public final class Activator extends AbstractUIPlugin {
	/** The singleton instance. */
	private static final AtomicReference<Activator> instance =
	    new AtomicReference<Activator>();

	/**
	 * Returns the symbolic name of this bundle.
	 * 
	 * @return The symbolic name of this bundle.
	 * @throws IllegalStateException If there is no active singleton instance.
	 */
	static String getSymbolicName() throws IllegalStateException {
		return getInstance().getBundle().getSymbolicName();
	}

	/**
	 * Returns the value of a system property.
	 * 
	 * @param key The name of the system property to return.
	 * @return The value of a system property.
	 * @throws IllegalStateException If there is no active singleton instance.
	 */
	static String getSystemProperty(String key) throws IllegalStateException {
		return getInstance().getBundle().getBundleContext().getProperty(key);
	}

	/**
	 * Returns the active singleton instance.
	 * 
	 * @return The active singleton instance.
	 * @throws IllegalStateException If there is no active singleton instance.
	 */
	private static Activator getInstance() throws IllegalStateException {
		Activator activator = instance.get();
		if (activator == null)
			throw new IllegalStateException();
		return activator;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(
	 *      org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		if (instance.compareAndSet(null, this))
			return;
		super.stop(context);
		throw new IllegalStateException();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(
	 *      org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		if (!instance.compareAndSet(this, null))
			throw new IllegalStateException();
		super.stop(context);
	}
}
